package com.tegtech.core.config;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.tegtech.common.utils.Threads;

/**
 * 线程池配置
 *
 * @author Jun
 **/
@Configuration
public class ThreadPoolConfig {
	
	// 核心线程数 (可用处理器的虚拟机的最大数量，不小于1)
	private int corePoolSize = Runtime.getRuntime().availableProcessors();

	// 队列最大长度
	private int queueCapacity = 100;

	// 线程池维护线程所允许的空闲时间
	private int keepAliveSeconds = 180;

	@Bean(name = "threadPoolTaskExecutor")
	public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        // 最大线程数
        pool.setMaxPoolSize(corePoolSize*2+1);
        // 核心线程池数
        pool.setCorePoolSize(corePoolSize);
        // 除核心线程外的线程存活时间
        pool.setKeepAliveSeconds(keepAliveSeconds);
        // 当线程空闲时间达到keepAliveSeconds时,销毁空闲线程
        pool.setAllowCoreThreadTimeOut(true);
        // 队列最大长度
        pool.setQueueCapacity(queueCapacity);
		// 线程池对拒绝任务(无线程可用)的处理策略 -- 队列满，线程被拒绝执行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		return pool;
	}

	/**
	 * 执行周期性或定时任务
	 */
	@Bean(name = "scheduledExecutorService")
	protected ScheduledExecutorService scheduledExecutorService() {
		return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
			@Override
			protected void afterExecute(Runnable r, Throwable t) {
				super.afterExecute(r, t);
				Threads.printException(r, t);
			}
		};
	}
}
